<?php


namespace Modules\Common\Lib\FeiShu;

class Base
{
    protected $app_id = '';
    protected $app_secret = '';

    public function __construct(array $info)
    {
        $this->app_id = $info['app_id'];
        $this->app_secret = $info['app_secret'];
    }

    protected function getTenantAccessToken(){
        $url = 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal';
        $res = $this->httpRequest($url,[
            'app_id'=>$this->app_id,
            'app_secret'=>$this->app_secret
        ],false,[
            "Content-Type: application/x-www-form-urlencoded"
        ]);
        return json_decode($res['body'],true);
    }


    protected function httpRequest($url, $data = null, $cookieFile = false, $headers = false, $proxy = false, $outTime = 5)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            if (is_array($data)) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
            } else {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }
        if ($cookieFile) {
            curl_setopt($curl, CURLOPT_COOKIEJAR, $cookieFile);
            curl_setopt($curl, CURLOPT_COOKIEFILE, $cookieFile);
        }
        if (is_array($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        if (is_array($proxy)) {
            curl_setopt($curl, CURLOPT_PROXY, $proxy['ip']);
            curl_setopt($curl, CURLOPT_PROXYPORT, $proxy['port']);
        } else if (is_string($proxy)) {
            curl_setopt($curl, CURLOPT_PROXY, $proxy);
        }
        curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_TIMEOUT, $outTime);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        $response = curl_exec($curl);
        $curlInfo = curl_getinfo($curl);
        $header = substr($response, 0, $curlInfo['header_size']); // 根据头大小获取头信息
        $body = substr($response, $curlInfo['header_size']);

        curl_close($curl);
        return [
            'header' => $header,
            'body' => $body,
            'request_header' => $curlInfo['request_header'],
            'url'=>$url
        ];
    }
}
